% function to average spectral estimates
% latest date 4.4.3

function[Pxx,F] = AvSpc(TS,ProcDef,sens);

block = ProcDef.block;
len = ProcDef.len;
[CalData,F] = GetCal(TS,ProcDef,sens);
WI = hanning(block);
p=0;
K = zeros([block 1]);
for i = 1:len,
   D = TS.matrix(p+1:p+block,sens);
	D1=cortre(D,0);
   K = K+fft(D1.*WI);
   p=p+block;
end;
K=K/len;
Pxx = K(2:(block/2)+1).*conj(CalData(1:block/2)');
return;



%----------helper function
function[CalData,frq1] = GetCal(TS,ProcDef,sens),
 
sensor = ProcDef.sensor;
Notchi = TS.filter.NotchF(2:5,:);		% NOTE ! there may be problems 
IsNotch = TS.filter.Filt(2:5,:);		%        if notch do not have right dimension..
oi = size(Notchi);
if oi(2) == 1,				% Nasty way. But it just works
	notch = Notchi(find(IsNotch)); 
elseif oi(2) == 2,
 	[x,y]=find(IsNotch);
   notch = Notchi(1:oi(2),1:oi(2));
end;
hpb1 = TS.filter.Filt(1);			% NOTE ! high pass filter is always disabled
prob = TS.probe.dist;	% 	 in calib05.m
gain = TS.probe.gain;
nband = TS.head.band;
nchannel = TS.head.nchannel;
block = ProcDef.block;
len = ProcDef.len;
TLine1 = ProcDef.TLine1;
TLRad1 = ProcDef.TLRad1;
TLFreq1 = ProcDef.TLFreq1;
nfrq=ProcDef.nfrq;
notchdef = ProcDef.notchdef;
Array = ProcDef.Array;

[TIndex,len] = GetSelArray(ProcDef);

if len < 1,
   fprintf('At least one stack required - error in GetSpectra\n');
   return;
end;


disp('GetSpectra -> Computing calibration table');

   if length(notch) < 1,%|
      notch = [0]; 		%| inserted 25.3.3
   end;						%| reason - in some rts fls notch = [0 0 0 0]
   
   nt=find(notch(:,notchdef(sens)));
   if length(nt)>0,
      nt=notch(nt);
   end;
[cplx,frq1] = calib05(sensor(sens),nband,block,prob(sens),nt,hpb1,gain(sens));
     
CalData = cplx;
